<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option
              v-for="dict in t_cfg_com_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tcfgcom:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:tcfgcom:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tcfgcom:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tcfgcomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="t_cfg_com_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="城市" align="center" prop="areaName"/>
      <el-table-column label="平台" align="center" prop="amount1Name"/>
      <el-table-column label="经销商" align="center" prop="amount2Name"/>
      <el-table-column label="商家" align="center" prop="amount3Name"/>
      <el-table-column label="教练" align="center" prop="amount4Name"/>
      <el-table-column label="达人" align="center" prop="amount5Name"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:tcfgcom:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:tcfgcom:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改分佣配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tcfgcomRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-tooltip placement="top-start">
              <template #content>
                选择平台：表示达人活动中平台的佣金比例；<br/>
                选择平台+经销商：表示店铺存在经销商、平台参与分佣时，<br/>
                平台与经销商各自的佣金比例（可按地区进行设置）<br/>
                选择平台+教练：表示教练、平台参与分佣时，<br/>
                平台与教练各自的佣金比例（可按地区进行设置）<br/>
              </template>
              <el-form-item label="类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择类型" @change="handleTypeChange"
                           :disabled="disableNum">
                  <!-- :disabled="form.merId>0" -->
                  <el-option
                      v-for="dict in t_cfg_com_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 2 || form.type === 3 || form.type === 4">
            <el-form-item label="地区" prop="areaCode">
              <el-cascader-area v-model="form.areaCode" :qrtType="1"></el-cascader-area>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="平台" prop="amount1">
              <div style="display: flex;">
                <el-input-number :controls="false" min="0" max="100" v-model.number="form.amount1"
                                 placeholder="请输入平台占比"
                                 @input="((val)=>{handleChange(val, 1)})"/>
                <span style="margin-left: 10px;">%</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经销商" prop="amount2">
              <div style="display: flex;">
                <el-input-number :controls="false" min="0" max="100" v-model.number="form.amount2"
                                 placeholder="请输入经销商占比"
                                 @input="((val)=>{handleChange(val, 2)})"/>
                <span style="margin-left: 10px;">%</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 1">
            <el-form-item label="达人" prop="amount5">
              <div style="display: flex;">
                <el-input-number :controls="false" v-model="form.amount5" :disabled="true"/>
                <span style="margin-left: 10px;">%</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 2">
            <el-form-item label="商家" prop="amount3">
              <div style="display: flex;">
                <el-input-number :controls="false" v-model="form.amount3" :disabled="true"/>
                <span style="margin-left: 10px;">%</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 3">
            <el-form-item label="商家" prop="amount3">
              <div style="display: flex;">
                <el-input-number :controls="false" min="0" max="100" v-model.number="form.amount3"
                                 placeholder="请输入商家占比"
                                 @input="((val)=>{handleChange(val, 3)})"/>
                <span style="margin-left: 10px;">%</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 3 || form.type === 4">
            <el-form-item label="教练" prop="amount4">
              <div style="display: flex;">
                <el-input-number :controls="false" v-model="form.amount4" :disabled="true"/>
                <span style="margin-left: 10px;">%</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tcfgcom">
import {listTcfgcom, getTcfgcom, delTcfgcom, addTcfgcom, updateTcfgcom} from "@/api/system/tcfgcom";

const {proxy} = getCurrentInstance();
const {t_cfg_com_type} = proxy.useDict('t_cfg_com_type');

const tcfgcomList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const disableNum = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    // cfgType: undefined,
    amount1: undefined,
    amount2: undefined,
    amount3: undefined,
    areaCode: undefined,
    comCatalogCode: undefined,
  },
  rules: {
    type: [
      {required: true, message: "类型不能为空", trigger: "change"}
    ],
    amount1: [
      {required: true, message: "平台不能为空", trigger: "change"}
    ],
    amount2: [
      {required: true, message: "经销商不能为空", trigger: "change"}
    ],
    amount3: [
      {required: true, message: "商家不能为空", trigger: "change"}
    ],
    amount4: [
      {required: true, message: "教练不能为空", trigger: "change"}
    ],
    amount5: [
      {required: true, message: "达人不能为空", trigger: "change"}
    ],
    // cfgType: [
    //   {required: true, message: "$comment不能为空", trigger: "change"}
    // ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询分佣配置列表 */
function getList() {
  loading.value = true;
  listTcfgcom(queryParams.value).then(response => {
    tcfgcomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    type: undefined,
    // cfgType: undefined,
    amount1: undefined,
    amount2: undefined,
    amount3: undefined,
    amount: 100,
    areaCode: undefined,
    comCatalogCode: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("tcfgcomRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  disableNum.value = 0
  reset();
  open.value = true;
  title.value = "添加分佣配置";
}

function handleTypeChange(value) {
  form.value.amount1 = undefined;
  form.value.amount2 = undefined;
  form.value.amount3 = undefined;
  form.value.amount4 = undefined;
  form.value.amount5 = undefined;
  form.value.amount6 = undefined;
  if (value === 1) {
    form.value.amount5 = 100;
  }
  if (value === 2) {
    form.value.amount3 = 100;
  }
  if (value === 3 || value === 4) {
    form.value.amount4 = 100;
  }
}

function handleChange(val, index) {
  if (val < 0) {
    val = 0;
  }
  if (val > 100) {
    val = 100;
  }

  if (index === 1) {
    form.value.amount1 = val;
  }
  if (index === 2) {
    form.value.amount2 = val;
  }
  if (index === 3) {
    form.value.amount3 = val;
  }
  if (index === 4) {
    form.value.amount4 = val;
  }
  if (index === 5) {
    form.value.amount5 = val;
  }
  if (index === 6) {
    form.value.amount6 = val;
  }

  if (form.value.type === 1) {
    form.value.amount5 = 100;
    if (form.value.amount1) {
      form.value.amount5 = form.value.amount5 - form.value.amount1
    }
    if (form.value.amount2) {
      form.value.amount5 = form.value.amount5 - form.value.amount2
    }
    if (form.value.amount3) {
      form.value.amount5 = form.value.amount5 - form.value.amount3
    }
    if (form.value.amount4) {
      form.value.amount5 = form.value.amount5 - form.value.amount4
    }
    if (form.value.amount6) {
      form.value.amount5 = form.value.amount5 - form.value.amount6
    }
  }
  if (form.value.type === 2) {
    form.value.amount3 = 100;
    if (form.value.amount1) {
      form.value.amount3 = form.value.amount3 - form.value.amount1
    }
    if (form.value.amount2) {
      form.value.amount3 = form.value.amount3 - form.value.amount2
    }
    if (form.value.amount4) {
      form.value.amount3 = form.value.amount3 - form.value.amount4
    }
    if (form.value.amount5) {
      form.value.amount3 = form.value.amount3 - form.value.amount5
    }
    if (form.value.amount6) {
      form.value.amount3 = form.value.amount3 - form.value.amount6
    }
  }
  if (form.value.type === 3 || form.value.type === 4) {
    form.value.amount4 = 100;
    if (form.value.amount1) {
      form.value.amount4 = form.value.amount4 - form.value.amount1
    }
    if (form.value.amount2) {
      form.value.amount4 = form.value.amount4 - form.value.amount2
    }
    if (form.value.amount3) {
      form.value.amount4 = form.value.amount4 - form.value.amount3
    }
    if (form.value.amount5) {
      form.value.amount4 = form.value.amount4 - form.value.amount5
    }
    if (form.value.amount6) {
      form.value.amount4 = form.value.amount4 - form.value.amount6
    }
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  disableNum.value = 1
  reset();
  const _id = row.id || ids.value
  getTcfgcom(_id).then(response => {
    form.value = response.data;
    if (response.data.amount1) {
      form.value.amount1 = parseFloat((form.value.amount1 * 100).toFixed(10))
    }
    if (response.data.amount2) {
      form.value.amount2 = parseFloat((form.value.amount2 * 100).toFixed(10))
    }
    if (response.data.amount3) {
      form.value.amount3 = parseFloat((form.value.amount3 * 100).toFixed(10))
    }
    if (response.data.amount4) {
      form.value.amount4 = parseFloat((form.value.amount4 * 100).toFixed(10))
    }
    if (response.data.amount5) {
      form.value.amount5 = parseFloat((form.value.amount5 * 100).toFixed(10))
    }
    if (response.data.amount6) {
      form.value.amount6 = parseFloat((form.value.amount6 * 100).toFixed(10))
    }
    open.value = true;
    title.value = "修改分佣配置";
  });
}

/** 提交按钮 */
function submitForm() {
  let totalTmp = form.value.amount1;
  if (form.value.amount2) {
    totalTmp = totalTmp + form.value.amount2
  }
  if (form.value.amount3) {
    totalTmp = totalTmp + form.value.amount3
  }
  if (totalTmp > 100) {
    proxy.$modal.msgError("比例不可大于等于100");
    return
  } else {
    if (form.value.amount1) {
      form.value.amount1 = (form.value.amount1 / 100).toFixed(2)
    }
    if (form.value.amount2) {
      form.value.amount2 = (form.value.amount2 / 100).toFixed(2)
    }
    if (form.value.amount3) {
      form.value.amount3 = (form.value.amount3 / 100).toFixed(2)
    }
    if (form.value.amount4) {
      form.value.amount4 = (form.value.amount4 / 100).toFixed(2)
    }
    if (form.value.amount5) {
      form.value.amount5 = (form.value.amount5 / 100).toFixed(2)
    }
    if (form.value.amount6) {
      form.value.amount6 = (form.value.amount6 / 100).toFixed(2)
    }
  }


  proxy.$refs["tcfgcomRef"].validate(valid => {

    if (valid) {

      if (form.value.id != null) {
        updateTcfgcom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTcfgcom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          if (form.value.amount1) {
            form.value.amount1 = parseFloat((form.value.amount1 * 100).toFixed(10))
          }
          if (form.value.amount2) {
            form.value.amount2 = parseFloat((form.value.amount2 * 100).toFixed(10))
          }
          if (form.value.amount3) {
            form.value.amount3 = parseFloat((form.value.amount3 * 100).toFixed(10))
          }
          if (form.value.amount4) {
            form.value.amount4 = parseFloat((form.value.amount4 * 100).toFixed(10))
          }
          if (form.value.amount5) {
            form.value.amount5 = parseFloat((form.value.amount5 * 100).toFixed(10))
          }
          if (form.value.amount6) {
            form.value.amount6 = parseFloat((form.value.amount6 * 100).toFixed(10))
          }
        })
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除分佣配置编号为"' + _ids + '"的数据项？').then(function () {
    return delTcfgcom(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tcfgcom/export', {
    ...queryParams.value
  }, `tcfgcom_${new Date().getTime()}.xlsx`)
}

getList();
</script>
